package com.example.beryl.proSystem;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.example.beryl.R;
import com.example.beryl.Util.HandlePublic;
import com.example.beryl.Util.ReceiveBroadCast;
import com.example.beryl.entity.Action;
import com.example.beryl.entity.Cutting.Cqbg;
import com.example.beryl.entity.UserData.Person;
import com.example.beryl.http.Net_cuttingRecord;
import com.example.beryl.http.Net_userData;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * 裁切报工
 */
public class cutingUpdate extends AppCompatActivity {
    private Toolbar toolbar;
    private ConstraintLayout clMain;
    private boolean mReceiverTag = false;//广播注册标志
    private ListView listView;
    private SimpleAdapter adapter;
    Cqbg cqpbg = new Cqbg();
    Person person = new Person();
    JSONArray jsonArray = null;
    private static final int CQRECALL = 1;
    private static final int EM = 2;
    private static final int UpdateForm = 3;
    private static final int RECALL = 4;
    ReceiveBroadCast mBroadcastReceiver = new ReceiveBroadCast();
    HandlePublic handlePublic = new HandlePublic();



    //注册广播，监听扫描枪
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        mReceiverTag = true;
        filter.addAction("com.android.server.scannerservice.broadcast"); //添加过滤条件，接收广播
        registerReceiver(mBroadcastReceiver, filter);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cuting_update);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        clMain = (ConstraintLayout) findViewById(R.id.cl_main);
        listView = (ListView) findViewById(R.id.listView);
        setSupportActionBar(toolbar);
        toolbar.setTitle("裁切报工");
        toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getGroupId()){
                    case 0:
                    case 1:
                    case 2:
                    case 3:{
                        Toast.makeText(cutingUpdate.this, "点了一下"+item.getTitle(), Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
                return false;
            }
        });

        if (Action.person != null)
        {
            final EditText editText = findViewById(R.id.Person);
            editText.setText(Action.person.cPsn_Name);
        }

        //广播回调
        mBroadcastReceiver.setScanHeadListener(getcode -> {
            mBroadcast(getcode);
        });

        //提交数据
        Button button = (Button) findViewById(R.id.submit1);
        button.setOnClickListener(view -> {
            try {
                Summit();
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        });

        //数据库回调
        handlePublic.setGetResult((what, t) -> GetResult(what,t));
    }


    //广播回调方法
    private void mBroadcast(String code)
    {
        switch(code.substring(0,2))
        {
            case "WO":
                EditText editText = (EditText) findViewById(R.id.Edit_account1);
                editText.setText(code);
                //handlePublic.startLoad(cutingUpdate.this);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getData(code);
                    }
                }).start();
                break;
            case "EM":
                //handlePublic.startLoad(cutingUpdate.this);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getPenson(code);
                    }
                }).start();
                break;
        }
    }

    //数据库回调后处理
    private void GetResult(int what,Object t) throws JSONException {
        EditText editText = (EditText) findViewById(R.id.Person);
        EditText editText1 = (EditText) findViewById(R.id.Shengyuchangdu);
        EditText editText2 = (EditText) findViewById(R.id.mianji);
        EditText editText3 = (EditText) findViewById(R.id.guige);
        EditText editText4 = (EditText) findViewById(R.id.Edit_account1);
        EditText editText5 =(EditText) findViewById(R.id.kuandu);
        String ret = handlePublic.dealDataBase((List)t);
        if (ret.contains("[") || ret.contains("{"))
        {
            switch (what)
            {
                case CQRECALL://流传单和已切信息
                    JSONArray jsonArray1 = handlePublic.getJsonArray(ret);
                    if (jsonArray1.length() == 1)
                    {
                        String LL = jsonArray1.getJSONObject(0).get("查询裁切报工").toString();
                        LL = handlePublic.JosnChange(LL);
                        cqpbg = (Cqbg) handlePublic.getEntity(LL,Cqbg.class);
                        String YQ = jsonArray1.getJSONObject(0).get("查询裁切已切料信息").toString();
                        jsonArray = new JSONArray(YQ);
                        setListView(jsonArray);
                        updateForm();//调用方法计算
                    }
                    else
                    {
                        handlePublic.Alert("返回数据异常：回调“CQRECALL",this);
                    }
                    break;
                case EM://人员
                    person = (Person) handlePublic.getEntity(ret,Person.class);
                    Action.person = person;
                    editText.setText(Action.person.cPsn_Name);
                    break;
                case UpdateForm:
                    editText3.setText(cqpbg.cSpecifucation);
                    JSONArray jsonArray2 = handlePublic.getJsonArray(ret);
                    editText1.setText(jsonArray2.getJSONObject(0).get("剩余长度").toString());
                    editText5.setText(jsonArray2.getJSONObject(0).get("剩余宽度").toString());
                    editText2.setText(jsonArray2.getJSONObject(0).get("剩余面积").toString());
                    break;
                case RECALL://提交
                    handlePublic.Alert("提交成功",this);
                    //取消输入框数据
                    editText.setText("");
                    editText1.setText("");
                    editText2.setText("");
                    editText3.setText("");
                    editText4.setText("");
                    editText5.setText("");
                    //表格数据清除
                    adapter = null;
                    listView.setAdapter(adapter);
                    break;
            }
        }else
        {
            handlePublic.Alert(ret,this);
        }
    }

    //得到裁切单数据
    private void getData(String data)
    {
        Net_cuttingRecord dbUtil = new Net_cuttingRecord();
        List<String> list = new ArrayList<>();
        list = dbUtil.CR_CommonMethod(Action.action.GetBarcode,data);
        handlePublic.setmHandler(CQRECALL,list);
    }

    //查找人员信息
    private void getPenson(String data) {

        Net_userData user = new Net_userData();
        List<String> list;
        list = user.User_CommonMethod(Action.action.GetPerson,data.split("-")[1]);
        handlePublic.setmHandler(EM, list);
    }

    //已切信息UI更改
    private void setListView(JSONArray jsonArray) throws JSONException {
        List<HashMap<String, String>> list = new ArrayList<>();
        listView.setVisibility(View.VISIBLE);
        list = getAllInfo(jsonArray);
        adapter = new SimpleAdapter(
                cutingUpdate.this,
                list,
                R.layout.activity_main2,
                new String[] { "规格型号", "裁切宽度"},
                new int[] { R.id.txt_Cno, R.id.txt_Cname});
                listView.setAdapter(adapter);
    }

    //已切信息处理，填充表格数据
    public List<HashMap<String, String>> getAllInfo(JSONArray jsonArray) throws JSONException {
        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> tempHash = new HashMap<String, String>();
        tempHash.put("规格型号", "规格型号");
        tempHash.put("裁切宽度", "裁切宽度");
        list.add(tempHash);
        for (int j = 0; j < jsonArray.length(); j ++) {
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("规格型号", jsonArray.getJSONObject(j).get("cSpecifution").toString());
            hashMap.put("裁切宽度", jsonArray.getJSONObject(j).get("dWidth").toString());
            list.add(hashMap);
        }
        return list;
    }

    //计算剩余
    public void updateForm()
    {
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("dLotQty",cqpbg.dLotQty);
        hashMap.put("dEffWidth",cqpbg.dEffWidth);
        hashMap.put("dEffWidth1",cqpbg.dEffWidth1);
        hashMap.put("dLength1",cqpbg.dLength1);
        String json = handlePublic.MakeJson(hashMap);
        Net_cuttingRecord dbUtil = new Net_cuttingRecord();
        //handlePublic.startLoad(cutingUpdate.this);
        new Thread(() -> {
            List<String> list;
            list = dbUtil.CR_CommonMethod(Action.action.SumFrom,json);
            handlePublic.setmHandler(UpdateForm,list);
        }).start();
    }


    //提交数据
    public void Summit() throws JSONException {
        EditText editText = (EditText) findViewById(R.id.kuandu);
        EditText editText1 = (EditText) findViewById(R.id.Shengyuchangdu);
        EditText editText2 = (EditText) findViewById(R.id.mianji);
        EditText editText3 = (EditText) findViewById(R.id.guige);
        EditText editText4 = (EditText) findViewById(R.id.Person);
        if ((editText.getText().toString().equals("")) && (editText1.getText().toString().equals("")) && (editText2.getText().toString().equals("")) && (editText3.getText().toString().equals("")))//判断是否有空表格
        {
            handlePublic.Alert("请把表格输入完整",this);
        }else
        {
            String NYR = handlePublic.Date(2).split(" ")[0];
            String isSync = "0";
            Double GNumber = 0.00;
            if (Double.parseDouble(editText2.getText().toString()) <= 0)
            {
                isSync = "1";
            }
            //总量相加
            for (int j = 0; j < jsonArray.length(); j ++)
            {
                GNumber += Double.parseDouble(jsonArray.getJSONObject(j).get("dReqQty").toString());
            }

                //组成数据提交集合
                HashMap<String,String> dict = new HashMap<>();
                dict.put("cMOLotNo",cqpbg.cMOLotNo);
                dict.put("cBatchNumber",cqpbg.cBatchNumber);
                dict.put("cMatNo",cqpbg.cMatNo);
                dict.put("cProductDepNo",cqpbg.cProductDepNo);
                dict.put("cSpecifucation",cqpbg.cSpecifucation);
                dict.put("dArea",editText2.getText().toString());
                dict.put("dLength",editText1.getText().toString());
                dict.put("dWidth",editText.getText().toString());
                dict.put("isSync",isSync);
                dict.put("times",handlePublic.Date(1));
                dict.put("ReportTime",handlePublic.Date(2));
                dict.put("NYR",NYR);
                dict.put("GNumber",String.valueOf(GNumber));
                dict.put("dLength1",cqpbg.dLength1);
                dict.put("Operator",editText4.getText().toString());

                //数据测试用
//                dict.put("cMOLotNo","1");
//                dict.put("cBatchNumber","1");
//                dict.put("cMatNo","1");
//                dict.put("cProductDepNo","1");
//                dict.put("cSpecifucation","1");
//                dict.put("dArea","1");
//                dict.put("dLength","1");
//                dict.put("dWidth","1");
//                dict.put("isSync","1");
//                dict.put("times","1");
//                dict.put("ReportTime","1");
//                dict.put("NYR","1");
//                dict.put("GNumber","1");
//                dict.put("dLength1","1");
//                dict.put("Operator","1");
                //检查是否有空值
                if(dict.containsValue("")) {
                    handlePublic.Alert("请把表格输入完整",this);
                }
                else
                {
                    //将字典变成json字符串
                    String josn = handlePublic.MakeJson(dict);
                    //handlePublic.startLoad(cutingUpdate.this);
                    //提交到数据库
                    new Thread(() -> {
                        List list = new ArrayList();
                        Net_cuttingRecord pro = new Net_cuttingRecord();

                        list = pro.CR_CommonMethod(Action.action.CR_Summit,josn);
                        handlePublic.setmHandler(RECALL,list);
                    }).start();
                }
        }
    }

    //按返回按钮时，取消广播注册
    @Override
    public void onBackPressed() {
        if (mReceiverTag) {
            unregisterReceiver(mBroadcastReceiver);
            finish();
        }
    }
    //状态栏菜单显示
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        //MenuItem menuItem = menu.findItem(R.id.toolbar_user);
        //menuItem.setVisible(false);
        setVisible(true);
        return true;
    }

    //通用弹出提示
//    private void Alert(String Message)
//    {
//        AlertDialog.Builder builder = new AlertDialog.Builder(CutingUpdate.this);
//        builder.setTitle("信息");
//        builder.setMessage(Message);
//        builder.setNegativeButton("确定",
//                (dialog, which) -> dialog.dismiss());
//        builder.create().show();
//    }
}